package com.ruoyi.common.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间工具类
 * 
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static String YearMothDayHHMMSS = "yyyy年MM月dd日HH时mm分ss秒";
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
    private static SimpleDateFormat sourceFormat = new SimpleDateFormat(YYYY_MM_DD);
    private static SimpleDateFormat sourceFormat1 = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
    private static SimpleDateFormat dateFormat = new SimpleDateFormat(YearMothDayHHMMSS);
    private static SimpleDateFormat dateFormat1 = new SimpleDateFormat(YYYY_MM_DD);

    public static String formatChinese(Date date){
        return dateFormat.format(date);
    }

    public static String formatDate(Date date){
        return dateFormat1.format(date);
    }

    public static String formatDate(LocalDateTime date){

        if(date == null){
            return null;
        }

        return date.format(DateTimeFormatter.ofPattern(YYYY_MM_DD));
    }

    public static String formatDateTime(LocalDateTime date){

        if(date == null){
            return null;
        }

        return date.format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
    }

    /**
     * 时间转为最小
     * @param originalDate
     * @return Date
     */
    public static Date minDate(Date originalDate){
        Calendar cal = Calendar.getInstance();
        cal.setTime(originalDate);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        long millisecond = hour * 60 * 60 * 1000 + minute * 60 * 1000 + second * 1000;
        cal.setTimeInMillis(cal.getTimeInMillis() - millisecond);

        if (true) {
            return cal.getTime();
        } else {
            cal.setTimeInMillis(cal.getTimeInMillis() + 23 * 60 * 60 * 1000 + 59 * 60 * 1000 + 59 * 1000);
        }
        return cal.getTime();
    }


    public static Date parseDate(final String str, final String... parsePatterns){
        try {
            return org.apache.commons.lang3.time.DateUtils.parseDate(str,parsePatterns);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("日期格式错误");
        }
    }


    /**
     * 时间转为最大
     * @param originalDate
     * @return Date
     */
    public static Date maxDate(Date originalDate){
        Calendar cal = Calendar.getInstance();
        cal.setTime(originalDate);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        long millisecond = hour * 60 * 60 * 1000 + minute * 60 * 1000 + second * 1000;
        cal.setTimeInMillis(cal.getTimeInMillis() - millisecond);

        if (false) {
            return cal.getTime();
        } else {
            cal.setTimeInMillis(cal.getTimeInMillis() + 23 * 60 * 60 * 1000 + 59 * 60 * 1000 + 59 * 1000);
        }
        return cal.getTime();
    }

    public static  String getConvertFormat(Date date){
        String dateString = sourceFormat.format(date);
        return dateString;
    }
    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (Exception e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate 最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * @desc  得到本季度的开始时间
     * @author fwx 2024/1/23 17:27
     **/
    public static String getQuarterBeginDate(){
        DateTime quarter = DateUtil.beginOfQuarter(new Date());
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }


    /**
     * @desc  得到本年的开始时间
     * @author fwx 2024/1/23 17:27
     **/
    public static String getYearBeginDate(){
        DateTime quarter = DateUtil.beginOfYear(new Date());
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc  得到去年最后一天
     * @author fwx 2024/3/2 14:45
     **/
    public static String getYearEndDate(int offset){
        DateTime quarter = DateUtil.beginOfYear(new Date()).offset(DateField.YEAR,offset).offset(DateField.DAY_OF_YEAR,-1);
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc  得到本周开始时间
     * @author fwx 2024/4/12 16:41
     **/
    public static String getWeekBeginDate(){
        DateTime quarter = DateUtil.beginOfWeek(new Date());
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc  得到偏移的年开始时间
     * @author fwx 2024/2/28 15:52
     **/
    public static String getYearBeginDate(int offset){
        DateTime quarter = DateUtil.beginOfYear(new Date()).offset(DateField.YEAR,offset);
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc 得到某一年的第一天
     * @author fwx 2024/1/26 13:47
     **/
    public static String getYearBeginDate(String year){
        Date date = DateUtil.parseDate(year + "-01-01");
        DateTime quarter = DateUtil.beginOfYear(date);
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc 得到某一年的最后一天
     * @author fwx 2024/1/26 13:47
     **/
    public static String getYearEndDate(String year){
        Date date = DateUtil.parseDate(year + "-12-31");
        DateTime quarter = DateUtil.endOfYear(date);
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc  得到某一月第一天 - 月格式 2024-03
     * @author fwx 2024/4/7 9:21
     **/
    public static String getMonthBeginDate(String month){
        Date date = DateUtil.parseDate(month + "-01");
        DateTime quarter = DateUtil.beginOfMonth(date);
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc 得到某一月的最后一天 - 月格式 2024-03
     * @author fwx 2024/1/26 13:47
     **/
    public static String getMonthEndDate(String month){
        Date date = DateUtil.parseDate(month + "-01");
        DateTime quarter = DateUtil.endOfMonth(date);
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }



    /**
     * @desc  得到本月的开始时间
     * @author fwx 2024/1/23 17:27
     **/
    public static String getMonthBeginDate(){
        DateTime quarter = DateUtil.beginOfMonth(new Date());
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc  得到去年同期月份开始时间
     * @author fwx 2024/2/29 10:02
     **/
    public static String getMonthBeginDate(int offsetY,int offsetM,int offsetDay){
        DateTime quarter = DateUtil.beginOfMonth(new Date())
                .offset(DateField.YEAR,offsetY)
                .offset(DateField.MONTH,offsetM)
                .offset(DateField.DAY_OF_YEAR,offsetDay);
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc  得到明天的日期
     * @author fwx 2024/2/18 15:02
     **/
    public static String getTomorrowStr(){
        DateTime quarter = DateTime.now().offset(DateField.DAY_OF_MONTH,1);
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc  得到今天的日期
     * @author fwx 2024/2/18 15:09
     **/
    public static String getNowStr(){
        DateTime quarter = DateTime.now();
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc  得到去年同期偏移日期
     * @author fwx 2024/2/29 10:27
     **/
    public static String getDayBeginDate(int offsetY,int offsetM){
        DateTime quarter = DateTime.now()
                .offset(DateField.YEAR,offsetY)
                .offset(DateField.DAY_OF_YEAR,offsetM);
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc  得到小时偏移时间
     * @author fwx 2024/3/2 16:33
     **/
    public static String getHour(int offsetH){
        DateTime quarter = DateTime.now()
                .offset(DateField.HOUR,offsetH);
        return quarter.toString(DatePattern.NORM_DATE_PATTERN);
    }

    /**
     * @desc  得到全部的开始时间
     * @author fwx 2024/1/23 17:27
     **/
    public static String getAllBeginDate(){
        return "2020-01-01";
    }

    public static void main(String[] args) {
    }
}
